import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_list_page_widget/common_list_page_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_single_choice_button_widget/common_single_choice_button_widget.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/utils/vg_date_time_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_time_util_lib.dart';

import '../../../app_main.dart';
import '../binding_add_admin_list_bean.dart';

/// 绑定添加管理员
/// 列表项
///
/// @author: zengxiangxi
/// @createTime: 1/7/21 4:50 PM
/// @specialDemand:
class BindingAddAdminListWidget extends StatefulWidget {
  final ValueNotifier<String> searchPageValueNotifier;
  final String hsn;
  final ValueChanged<List<SelectAddRecordsBean>> listClickCallback;//带参数回调
  BindingAddAdminListWidget({Key key, this.hsn, this.listClickCallback, this.searchPageValueNotifier}) : super(key: key);
  @override
  _BindingAddAdminListWidgetState createState() => _BindingAddAdminListWidgetState();
}

class _BindingAddAdminListWidgetState extends State<BindingAddAdminListWidget> {
  ValueNotifier<String> searchPageValueNotifier;
  CommonListPageWidgetState<SelectAddRecordsBean,BindingAddAdminListBean> listState;
  CommonSingleChoiceStatus statusType;
  List<SelectAddRecordsBean> listSelectItemBean = List();

  @override
  void initState() {
    super.initState();
    searchPageValueNotifier = widget?.searchPageValueNotifier;
    searchPageValueNotifier?.addListener(_refreshSearch);
      searchPageValueNotifier?.value == null || searchPageValueNotifier?.value == "" ? "" :searchPageValueNotifier?.value;
    statusType = CommonSingleChoiceStatus.unSelect;
  }

  void _refreshSearch(){
    // if(searchPageValueNotifier?.value==null||searchPageValueNotifier?.value==""){
    //   searchPageValueNotifier?.value = "%-%";
    // }
    listState?.viewModel?.refresh();
    setState(() { });
  }

  @override
  Widget build(BuildContext context) {
    return CommonListPageWidget<SelectAddRecordsBean,BindingAddAdminListBean>(
      netUrl:ServerApi.BASE_URL + "app/appTerminalAddAdminList",
      itemBuilder: (BuildContext context, int index,
          SelectAddRecordsBean itemBean) {
        return _toListItemWidget(itemBean);
      },
      parseDataFunc: (VgHttpResponse resp) {
        return BindingAddAdminListBean.fromMap(resp?.data);
      },
      httpType: VgHttpType.get,
      stateFunc: (state) {
        this.listState = state;
      },
      queryMapFunc: (int page) => {
        "authId": UserRepository.getInstance().authId ?? "",
        "hsn": widget?.hsn,
        // "size": 20,
        // "fuid": "",
        "searchName":searchPageValueNotifier?.value == null || searchPageValueNotifier?.value == "" ? "" :searchPageValueNotifier?.value,
      },
    );
    // return _toListItemWidget(itemBean);
  }

  Widget _toListItemWidget(SelectAddRecordsBean itemBean) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: (){
        if(itemBean?.statusType == CommonSingleChoiceStatus.selected){
          itemBean?.statusType = CommonSingleChoiceStatus.unSelect;
          listSelectItemBean?.remove(itemBean);
        }else {
          itemBean?.statusType = CommonSingleChoiceStatus.selected;
          listSelectItemBean.add(itemBean);
        }
        setState(() {

        });
        widget.listClickCallback.call(listSelectItemBean);
      },
      child: Container(
        height: 64,
        margin: const EdgeInsets.symmetric(horizontal: 15),
        child: Row(
          children: <Widget>[
            CommonSingleChoiceButtonWidget(itemBean?.statusType??statusType),
            SizedBox(
              width: 15,
            ),
            ClipOval(
              child: VgCacheNetWorkImage(
                showOriginEmptyStr(itemBean?.napicurl) ??
                    (itemBean?.napicurl ?? ""),
                defaultErrorType: ImageErrorType.head,
                defaultPlaceType: ImagePlaceType.head,
                height: 40,
                width: 40,
              ),
            ),
            SizedBox(
              width: 10,
            ),
            Expanded(
              child: _toColumnWidget(itemBean),
            )
          ],
        ),
      ),
    );
  }

  Widget _toColumnWidget(SelectAddRecordsBean itemBean) {
    String roleLable = "";
    if(itemBean?.roleid=="10"){
      roleLable = "员工";
    }else if(itemBean?.roleid=="90"){
      roleLable = "管理员";
    }else if(itemBean?.roleid=="99"){
      roleLable = "超级管理员";
    }
    String _lastTime = VgDateTimeUtils.getFormatTimeStr(itemBean?.lasttime);
    return Container(
      height: 40,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Row(
            children: <Widget>[
              Text(
                "${itemBean?.nick??"员工"}",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color:
                  ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                  fontSize: 15,
                ),
              ),
              SizedBox(
                width: 8,
              ),
              Container(
                height: 16,
                padding: const EdgeInsets.symmetric(horizontal: 4),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(2),
                    color: ThemeRepository.getInstance()
                        .getMinorYellowColor_FFB714()
                        .withOpacity(0.1)),
                child: Center(
                  child: Text(
                    roleLable ?? "",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: ThemeRepository.getInstance()
                            .getMinorYellowColor_FFB714(),
                        fontSize: 10,
                        height: 1.2),
                  ),
                ),
              ),
              _toPhoneWidget(itemBean)
              // Spacer(),
              // Text(
              //   "${itemBean?.loginphone??""}",
              //   maxLines: 1,
              //   overflow: TextOverflow.ellipsis,
              //   style: TextStyle(
              //     color: VgColors.INPUT_BG_COLOR,
              //     fontSize: 12,
              //   ),
              // )
            ],
          ),
          Row(
            children: <Widget>[
              // Text(
              //   "${itemBean?.loginphone??""}",
              //   maxLines: 1,
              //   overflow: TextOverflow.ellipsis,
              //   style: TextStyle(
              //     color: VgColors.INPUT_BG_COLOR,
              //     fontSize: 12,
              //   ),
              // ),
              // Spacer(),
              _lastTimeJudgeWidget(_lastTime),
            ],
          )
        ],
      ),
    );
  }

  Widget _lastTimeJudgeWidget(String _lastTime) {
    if (_lastTime!=null && _lastTime!="") {
      return Text(
        "${"${_lastTime}登录APP"}",
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(
          color: VgColors.INPUT_BG_COLOR,
          fontSize: 11,
        ),
        textAlign: TextAlign.right,
      );
    }
    return Text(
      "未登录APP",
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
      style: TextStyle(
        color: Color(0xFFF95355),
        fontSize: 11,
      ),
      textAlign: TextAlign.right,
    );
  }

  Widget _toPhoneWidget(SelectAddRecordsBean itemBean) {
    return Offstage(
      offstage: itemBean?.loginphone == null || itemBean?.loginphone?.isEmpty,
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          _call(itemBean?.loginphone);
        },
        child: Container(
          width: 16,
          height: 16,
          margin: const EdgeInsets.only(left: 4, right: 10),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(2),
              color: ThemeRepository.getInstance()
                  .getPrimaryColor_1890FF()
                  .withOpacity(0.1)),
          child: Icon(
            Icons.phone,
            size: 10,
            color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
          ),
        ),
      ),
    );
  }

  void _call(String phone) async {
    if (StringUtils.isEmpty(phone)) {
      return;
    }
    if (phone.length != DEFAULT_PHONE_LENGTH_LIMIT) {
      VgToastUtils.toast(AppMain.context, "手机号不正确");
      return;
    }
    if (await canLaunch("tel:" + phone)) {
      await launch("tel:" + phone);
    } else {
      throw 'Could not launch $phone';
    }
  }

  ///时间秒转字符串
  static String getFormatTime(int timeSecond) {
    if (timeSecond == null) {
      return null;
    }
    return DateUtil.formatDateMs(timeSecond * 1000, format: "HH:mm");
  }
}
